<?

require_once('dpvr.config.php');
require_once('dpvr.vars.php');
require_once('phptvdb-1.0.1/TVDB.php');
require_once('classes/tvrage.php');
require_once('dpvr.classes.php');
require_once('dpvr.nzb.php');
require_once('dpvr.logging.php');

$included_dpvr_xml_php = true;
require_once('dpvr.xml.php');

$silent = false;

function print_ajax($message) {
  global $do_show;
  
  if ($do_show !== false)
    print $message;
}

$tvrage_up = true;
$tvdb_up = true;
 
function processTV () {
 
  global $config, $configData, $_REQUEST;
  
  print_log('======== Begin Run ==========');

  if(!file_exists($config['dpvr_dir'].$configData['xml_file'])) {
    print_log("ERROR: Couldn't find ".$config['dpvr_dir'].$configData['xml_file']);
    return;
  }

  // make my XML object
  $tvXML = simplexml_load_file($config['dpvr_dir'].$configData['xml_file']);

  if ($_REQUEST['seriesID'] > 0)
    $shows = array(new ShowInfo($tvXML, $_REQUEST['seriesID']));
  else
    $shows = ShowInfo::allShows($tvXML);

  $showsAdded = 0;
  $mailString = '';
    
  foreach ($shows as $showInfo) {
  
    print_log('Processing '.$showInfo->seriesName);
  
    $showInfo->update();
  
    // if we got some info then save it into tv.xml
    if ($showInfo->showTVDB !== false) {
      $showInfo->saveToXML($showXML);
      saveXML($tvXML);
    }
   
    // if downloaded episode is blank, start at 1x0
    if ((int)$showInfo->dlSeason == 0 || (int)$showInfo->dlEpisode == 0) {
      $curSeason = 1;
      $curEpisode = 0;
   
    // usually we just start from the last downloaded episode
    } else {
      $curSeason = $showInfo->dlSeason;
      $curEpisode = $showInfo->dlEpisode;
    }
   
    // if we're more than one episode behind
    // only do this if we know there are more episodes, if we're guessing we only want to do it on the correct date (below)
    while ($showInfo->oneEpisodeBehind($curSeason, $curEpisode) === false && !empty($showInfo->nextSeason) && !empty($showInfo->nextEpisode)) {

      // get the next episode after the one we've already downloaded
      $nextEpisodeInfo = $showInfo->TVDB_nextEpisode($curSeason, $curEpisode);
      // if we can't get the next episode from tvnzb then assume it's the next one in line
      if ($nextEpisodeInfo === false)
        $nextEpisodeInfo = array('season' => $curSeason, 'episode' => $curEpisode+1);

      // download that episode (which automatically updates dlSeason and dlEpisode inside $showInfo)
      $nzbDownloaded = downloadShow($showInfo, $nextEpisodeInfo['season'], $nextEpisodeInfo['episode']);
     
      // do stuff based on whether dl was successful
      if ($nzbDownloaded[0]) {
        if ($nzbDownloaded[1] == 'newzbin') {
          // count newzbin download cause we have to throttle them
          $showsAdded++;
        }
        
        // append to the mail string
        $mailString .= $nzbDownloaded[2];

        //newzbin has a limit of 5 nzb's per minute
        if($showsAdded % 5 == 0 && $showsAdded != 0) {
            print "sleeping\n";
            sleep(60);
        }
        
      }
   
      // regardless of whether we found one or not we need to keep looking
      $curSeason = $nextEpisodeInfo['season'];
      $curEpisode = $nextEpisodeInfo['episode'];
    }

    // for shows that we don't know the next date just fake a date so they don't get checked
    if ((int)$showInfo->nextAirdate == 0)
      $nextAirdate = strtotime('+1 year'); // later
    else
      $nextAirdate = (int)$showInfo->nextAirdate;
      
    // if we're one episode behind and it airs today or previous OR we're forcing it
    if ( (strtotime(date('M d Y')) >= strtotime(date('M d Y', $nextAirdate))) || !empty($_REQUEST['seriesID'])) {
    
      // if we don't know what the next ep is then just try current+1
      if (empty($showInfo->nextSeason) || empty($showInfo->nextEpisode)) {
        $nextSeason = $curSeason;
        $nextEpisode = $curEpisode+1;
        $nextAirdate = 0;
      } else {
        $nextSeason = (int)$showInfo->nextSeason;
        $nextEpisode = (int)$showInfo->nextEpisode;
        $nextAirdate = (int)$showInfo->nextAirdate;
      }
    
      // download it!
      $nzbDownloaded = downloadShow($showInfo, $nextSeason, $nextEpisode, $nextAirdate);
     
      // if the download was successful
      if ($nzbDownloaded[0]) {

        // update next episode (it'll be blank if we can't find the next ep info)
        $nextEpisode = $showInfo->TVDB_comingEpisode($nextSeason, $nextEpisode);
        $showInfo->nextSeason = $nextEpisode['season'];
        $showInfo->nextEpisode = $nextEpisode['episode'];
        $showInfo->nextAirdate = $nextEpisode['airdate'];
        $showInfo->nextEpName = $nextEpisode['name'];
        
        $mailString .= $nzbDownloaded[2];
        
      }
    } else
      print_log("  Show doesn't air today, skipping");

    $showInfo->saveToXML();

    //send email
    if($config['mail'] && $mailString != '') {
      $mail_sent = mail($config['mail_to'], '[hellaVCR] ' . substr_count($mail_string, "\n") . ' episodes found', "The following episodes have been queued in hellanzb:\n\n" . $mail_string, 'From: hellaVCR <hellaVCR@faketown.com>');
      print_log('  emailing queue' . $configData['debug_separator'] . ($mail_sent ? 'done' : 'FAIL')); 
    }

  }

  saveXML($tvXML);
  
  print_log("\n");
  
}

if (!$dpvr_include)
  processTV();

?>
